# -- coding: UTF-8 --

# vowei.py - vowei integration for svn
#
# copyright 2010 Shi Yimin <yimin_shi@hotmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License versoin 2 or any later version
import sys, subprocess, ConfigParser, re
import locale
import vowei_hook_common

class svn_hook(vowei_hook_common.vowei_hook_base):
    def __init__(self, filename = 'vowei_hook.cfg'):
        self.filename = filename
        vowei_hook_common.vowei_hook_base.__init__(self)

    def read_config(self):
        self.debug_print('read_config')
        try:
            self.config = ConfigParser.ConfigParser()
            self.config.read(self.filename)
            self.svnlook_path = self._read_config(
                'default', 'svnlook', 
                '"c:\\program files\\subversion\\bin\\svnlook"')

            # Fix white spaces in path
            if self.svnlook_path[0] != '"':
                self.svnlook_path = ('"%s"') % self.svnlook_path

            self.path = self._read_config(
                'default', 'path', 'http://www.vowei.com/Comment/PostComments')
            self.user = self._read_config(
                'default', 'user', 'Administrator')
            self.password = self._read_config(
                'default', 'password', 'User@123')
        except Exception, e:
            self.debug_print(('Error read config file %s, exception: %s') % 
                             (self.filename, e))
            raise

    def _read_config(self, section, key, defaultValue):
        value = defaultValue
        if self.config.has_option(section, key):
            value = self.config.get(section, key)

        return value

    def configitems(self, section):
        if self.config.has_section(section):
            return self.config.items(section)
        else:
            return None

committer_re = re.compile('^([a-zA-Z0-9_]+)\\s*(\\n|$)')
ANNONYMOUS_USER_NAME = 'annony'
def get_svn_committer(message):
    match = committer_re.search(message)
    if not match:
        return ANNONYMOUS_USER_NAME
    else:
        return match.group(1)

def hook(repos, rev, vw):
    svnlook_path = vw.svnlook_path
    cmd = svnlook_path + " info -r " + rev + " " + repos
    vw.debug_print(cmd)
    process = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    vw.debug_print('Opened pipe')
    message = process.stdout.read()
    lines = message.splitlines()

    vw.debug_print('begin get commit message')
    if len(lines) < 3:
        vw.debug_print("Ignoring commit message less than 3 svnlook lines")
        sys.exit(0)

    commiter = get_svn_committer(lines[0])
    vw.debug_print(commiter);
    # remove committer name from message
    if ( commiter != ANNONYMOUS_USER_NAME ):
        del lines[0]

    # remove commit date
    del lines[0]
    # remove change set id
    del lines[0]    
        
    ids = set()
    commentText = ''
    for line in lines:
        ids.update(vw.find_work_item_ids(line))
        commentText = commentText + line
        
    # get detailed change lists
    cmd = svnlook_path + " changed -r " + rev + " " + repos
    process = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)    
    commentText = commentText + '\n\n' + process.stdout.read()
    
    vw.debug_print(commentText)
    
    if ids:
        vw.debug_print('begin create comments')
        comments = vw.create_comments(commentText.decode(locale.getpreferredencoding()), commiter, rev, ids)

        if ( len(comments) > 0 ) :
            vw.debug_print('begin post comments')
            vw.post_data_via_ntlm_channel(vw.path, vw.user, vw.password, comments)

if __name__ == '__main__':
    repos = sys.argv[1]
    rev = sys.argv[2]
    cfg_file = sys.argv[3]
    vw = svn_hook(cfg_file)
    
    try:
        hook(repos, rev, vw)
    except Exception, err:
        vw.debug_print(('Encountted error %s') % err)
